var canvas  // canvas variable

var currentScreen = "main menu";
var previousScreen = "main menu";

var graphicsPath = "graphics/";
var imageLoadCounter = 0;
var imageLoadTotal = 0;
var width = 640;
var height = 480;
var speed = 0;
var gravity = 0.3;
var wind = 1

var myTurn = true;
var penguinsTurnCounter = 0;
var enemiesTurnCounter = 0;

var points = new Array();
var terrain = new Array();
var fancystuff = new Array();
var penguins = new Array();
var enemies = new Array();
var bullets = new Array();
var tombstones = new Array();

var directionX = 0;
var diretctionY = 0;
var directionAngle = 0;

var pointer = null;

var font = '18px Verdana'

var isShooting = false;

var powerBar;

        // define a dictionary to load images which contains one array for each menu
        // the array is two-dimensional structured in this way:
        // graphicsArray[x][0] is the image object of img
        // graphicsArray[x][1] is the name/id of x (Note: Also path!, so path = id.png)
        // graphicsArray[x][2] is the x coordinate of x
        // graphicsArray[x][3] is the y coordinate of x

var menus = [0,1,2,3,4,9,10]
var graphics = [

    // Main Menu
    // graphics[0] is the main menu array
    [           
        [null, "background", 0, 0],
        [null, "play", width/2-250/2, 225],
        [null, "help", width/2-250/2, 280],       
        [null, "credits", width/2-250/2, 340],
        [null, "playover", width/2-250/2, 212],
        [null, "helpover", width/2-250/2, 270],
        [null, "creditsover", width/2-246/2, 327]
    ],
    
    // Credits Menu
    // graphics[1] is the credits menu array
    [
        [null, "background", 0, 0],
        [null, "creditsbox", width/2-250/2, 220],
        [null, "backarrow", 425, 355],
        [null, "backarrowover", 383, 316]
    ],
    
    
    //GamePlay 
    // graphics[2] is the gameplay window array 
    [
       
        [null, "gameplay", 0,0],
        [null, "pausebutton", width/2-208/2, 0],
        [null, "windarrow", width-100, 5],
        [null, "levelbackground", 0, 0],
        [null, "pausebuttonover", width/2-228/2, 0]
       
    ],
    
    // Help Menu
    // graphics[3] is the help menu array
    [
        [null, "background", 0, 0],
        [null, "scroll", 0, 0],
        [null, "helpbox", width/2-250/2, 220], 
        [null, "backarrow", 425, 355],
        [null, "backarrowover", 383, 316]
    ],
    
    
    //Pause Menu
    //graphics[4] is the pause button
    
    [
        [null, "scroll", 0, 0],
        [null, "resume", width/2-250/2, 225],
        [null, "help", width/2-250/2, 280],       
        [null, "exit", width/2-250/2, 341],
        [null, "resumeover", width/2-250/2, 214],
        [null, "helpover", width/2-250/2, 270],
        [null, "exitover", width/2-250/2, 333]
    ],
    
    //Penguin
    //graphics[5] are the penguins
    [
        [null, "penguin_still"],
        [null, "penguin_grenade"],
        [null, "penguin_rocket"],
        [null, "penguin_rifle"]
    ],
    
    //Pandas
    //graphics[6] are the pandas
    
    [
        [null, "panda"]
    ],
    
    //Bullets/projectiles
    //graphics[7] are the bullets
    [
        [null, "grenade"],
        [null, "boom"]
    ],

    //Tombstones
    //graphics[8] are the death images
    [
        [null, "tombstone_penguin"],
        [null, "tombstone_panda"],
        [null, "pointer"]
    ],

    // Victory Menu
    // graphics[9] is the Epic Win menu array
    [
        [null, "epicwinmenu", 0, 0],
        [null, "backarrow", 425, 355],
        [null, "backarrowover", 383, 316]
    ],

    // Game Over Menu
    // graphics[10] is the Game Over menu array
    [
        [null, "background", 0, 0],
        [null, "scroll", 0, 0],
        [null, "gameover", width/2-433/2, 210],    
        [null, "backarrow", 425, 355],
        [null, "backarrowover", 383, 316]
    ]
    
];


function init() {

    canvas = jc.canvas('canvas').start(60); // iniatialize the canvas
    
    canv = document.getElementById("canvas");
    canv.style.cursor = "url(graphics/pawcursor.cur),crosshair"

    canv.addEventListener("mousedown", eventMouseClick, false);
    canv.addEventListener("mousemove", eventMouseMove, false);
    
    
    ImageLoader();
    
   // out('loading images...');
    waitForImageLoad();
  //  out('done');
}


function main() {
//    out('starting the main function');
    
    makeAllImageObjects();
    
    setAllImagesNotVisible();
    
    drawMainMenu();
    
}


// Create and Draw every image object, then set every object non-visible
// It just creates objects up to graphics[4], because after that there are penguins/enemies
function makeAllImageObjects() {
    for (j=0; j < menus.length; j++) {
        for (i=0; i < graphics[menus[j]].length; i++) {
            jc.image(graphics[menus[j]][i][0], graphics[menus[j]][i][2], graphics[menus[j]][i][3]).id(graphics[menus[j]][i][1]+j); 
        }
    }    
}


// Sets every image object non-visible
// to improve performance, it is possible to call the function with the index,
// then it will set non-visible only the images of that array (ex.: images of a menu window)
function setAllImagesNotVisible(index) {
    if (index == null) {
        for (j=0; j < menus.length; j++) {
            for (i=0; i<graphics[menus[j]].length; i++) {
                jc("#"+graphics[menus[j]][i][1]+j).visible(false);
            }
        }
    }
    else {
        j = index
        for (i=0; i<graphics[j].length; i++) {
            jc("#"+graphics[j][i][1]+j).visible(false);
        }
    }
}

function drawMainMenu() {
    currentScreen = "main menu"
    
    canv = document.getElementById("canvas");
    canv.style.cursor = "url(graphics/pawcursor.cur),crosshair"
    
    var j = 0 
    for (i=0; i < 4; i++) {
        jc("#"+graphics[j][i][1]+j).visible(true);
    }
    
    // go to play if Play Button is clicked
    jc("#"+graphics[0][1][1]+"over"+j).click(
        function() { 
            previousScreen = "main menu"; 
            setAllImagesNotVisible(0); 
            drawGameWindow(); 
        }
    );
    // glow effect for mouse over Play Button
    jc("#"+graphics[0][1][1]+j).mouseover(
        function() {
            jc("#"+graphics[j][1][1]+j).visible(false);
            jc("#"+graphics[j][1][1]+"over"+j).visible(true);
        }
    );
    // no effect for mouse out Play Button
    jc("#"+graphics[0][1][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "main menu" ) {
                jc("#"+graphics[j][1][1]+"over"+j).visible(false);
                jc("#"+graphics[j][1][1]+j).visible(true);
            }
        }
    );
    // go to help menu if Help Button is clicked
    jc("#"+graphics[0][2][1]+"over"+j).click(
        function() { 
            previousScreen = "main menu"; 
            setAllImagesNotVisible(0); 
            drawHelpMenu(); 
        }
    );
    // glow effect for mouse over Help Button
    jc("#"+graphics[0][2][1]+j).mouseover(
        function() {
            jc("#"+graphics[j][2][1]+j).visible(false);
            jc("#"+graphics[j][2][1]+"over"+j).visible(true);
            
        }
    );
    // no effect for mouse out Help Button
    jc("#"+graphics[0][2][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "main menu" ) {
                jc("#"+graphics[j][2][1]+"over"+j).visible(false);
                jc("#"+graphics[j][2][1]+j).visible(true);
            }
        }
    );
    // go to credits menu if the Credits Button is clicked
    jc("#"+graphics[0][3][1]+"over"+j).click( 
        function() { 
            previousScreen = "main menu";
            setAllImagesNotVisible(0);
            drawCreditsMenu();
        }
    );
    // glow effect for mouse over Credits Button
    jc("#"+graphics[0][3][1]+j).mouseover(
        function() {
            jc("#"+graphics[j][3][1]+j).visible(false);
            jc("#"+graphics[j][3][1]+"over"+j).visible(true);
        }
    );
    // no effect for mouse out Credits Button
    jc("#"+graphics[0][3][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "main menu") {
                jc("#"+graphics[j][3][1]+"over"+j).visible(false);
                jc("#"+graphics[j][3][1]+j).visible(true);
            }
        }
    );
}

function drawCreditsMenu() {
    currentScreen = "credits menu";
    
    
    canv = document.getElementById("canvas");
    canv.style.cursor = "url(graphics/pawcursor.cur),crosshair"
    
    var j = 1
    for (i=0; i < graphics[j].length-1; i++) {
        jc("#"+graphics[j][i][1]+j).visible(true);
    }
    
    
    // go back to Main Menu if the back arrow is pressed
    jc("#"+graphics[j][2][1]+"over"+j).click(
        function() { 
            previousScreen = "credits menu"; 
            setAllImagesNotVisible(1); 
            drawMainMenu(); 
        }
    );
    
    jc("#"+graphics[j][2][1]+j).mouseover(
        function() {
            jc("#"+graphics[j][2][1]+j).visible(false);
            jc("#"+graphics[j][2][1]+"over"+j).visible(true);
        }
    );
    
    jc("#"+graphics[j][2][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "credits menu") {
                jc("#"+graphics[j][2][1]+"over"+j).visible(false);
                jc("#"+graphics[j][2][1]+j).visible(true);
            }
        }
    );
}

function drawHelpMenu() {
    currentScreen = "help menu";

    canv = document.getElementById("canvas");
    canv.style.cursor = "url(graphics/pawcursor.cur),crosshair"

    var j = 3;
	
    if (previousScreen == "pause menu") {
        jc("#"+graphics[j][1][1]+j).visible(true); // scroll background
    }
    else {
        jc("#"+graphics[j][0][1]+j).visible(true); // full background
    }
    
    for (i=2; i < graphics[j].length-1; i++) {
        jc("#"+graphics[j][i][1]+j).visible(true);
       // out("#"+graphics[j][i][1]+j)
    }
    
    // go back to Main Menu if the back arrow is pressed
    jc("#"+graphics[j][3][1]+"over"+j).click(
        function() { 
            setAllImagesNotVisible();
            oldPreviousScreen = previousScreen; 
            previousScreen = "help menu"; 
            if (oldPreviousScreen == "main menu") { 
                drawMainMenu();
            } else if (oldPreviousScreen == "pause menu") {
                drawGameWindow();
                drawPauseMenu();
            } else { 
                out('error, im trying to get to a previous menu and i dont know how Q_Q') 
            }
        }
    );
    
    jc("#"+graphics[j][3][1]+j).mouseover(
        function() {
            jc("#"+graphics[j][3][1]+j).visible(false);
            jc("#"+graphics[j][3][1]+"over"+j).visible(true);
        }
    );
    
    jc("#"+graphics[j][3][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "help menu") {
                jc("#"+graphics[j][3][1]+"over"+j).visible(false);
                jc("#"+graphics[j][3][1]+j).visible(true);
            }
        }
    );
}

function drawGameWindow(){
    currentScreen = "game window"
    
    canv = document.getElementById("canvas");
    canv.style.cursor = "url(graphics/crosshair.cur),crosshair"
    
    var j = 2;
    for (i=1; i < graphics[j].length; i++) {
      out("adding "+graphics[j][i]+j);
        jc("#"+graphics[j][i][1]+j).visible(true);
    }
    
    jc("#"+graphics[2][3][1]+j).down('bottom');
    
    
    if (previousScreen != "pause menu" && previousScreen != "help menu") {
        randomPointsList()
        drawTerrain();
        
        downAll(terrain)
        
        windLabel = jc.text("Wind", 520, 50, 'rgb(152,0,0)', true).id("windLabel")
        jc("#windLabel").font(font)
        fancystuff.push(windLabel)
        
        
        // POWER BAR
        powerBarX = 30
        powerBarY = 440
        powerBarWidth = 180
        powerBarHeight = 15
        colors = [[0,'rgb(255,255,0)'], [0.5,'rgb(255,0,0)'], [1,'rgb(0,0,0)']];
        gradient = jc.lGradient(powerBarX, 0, powerBarX+powerBarWidth, 0,colors);
        powerBar = jc.rect(powerBarX, powerBarY, powerBarWidth, powerBarHeight, gradient, 1).id("powerBar");
        jc.rect(powerBarX-2, powerBarY-2, powerBarWidth+4, powerBarHeight+4, false);
        jc.rect(powerBarX-1, powerBarY-1, powerBarWidth+2, powerBarHeight+2, false);
        jc.text("POWER", powerBarX, powerBarY+powerBarHeight-25, 'rgb(0,0,0)', true).id("powerBarLabel");
        jc("#powerBarLabel").font(font);
        
        // ANGLE THING
        angleX = 580
        angleY = 430
        angleR = 40
        
        jc.circle(angleX, angleY, angleR);
        jc.circle(angleX, angleY, angleR+1);
        jc.line(   [[angleX-angleR+10, angleY-5],[angleX+angleR-20,angleY-5],[angleX+angleR-20,angleY-15],[angleX+angleR-5, angleY],
                            [angleX+angleR-20,angleY+15],[angleX+angleR-20,angleY+5],[angleX-angleR+10,angleY+5]] , 'rgb(160,0,0)', true).id("angle")
        jc.circle(angleX, angleY, 1);
        
        directionX = angleX;
        directionY = angleY;
        directionAngle = 0;
        
        jc.text("ANGLE", angleX-30, angleY-46, 'rgb(0,0,0)', true).id("angleLabel");
        jc("#angleLabel").font(font);
        
        
        penguin1 = new Penguin(50, points[50][1]);
        penguin2 = new Penguin(150, points[150][1]);
        pointer = new Pointer(parseInt(penguins[penguinsTurnCounter].x), parseInt(penguins[penguinsTurnCounter].y))
        
        panda1 = new Panda(width-50, points[width-50][1]);
        panda2 = new Panda(width-150, points[width-150][1]);
        
        updateWind();
        
        jc("#"+graphics[2][4][1]+j).down('bottom');

    }
    
    

    
    // go to Pause menu if the Pause button is pressed
    jc("#"+graphics[j][1][1]+"over"+j).click(
        function() { 
            previousScreen = "game window"; 
            downAll(fancystuff)
            drawPauseMenu(); 
        } // dont clear images to keep game screen as background
    );
    
    jc("#"+graphics[j][1][1]+"over"+j).keypress(
        function() { 
            previousScreen = "game window"; 
            setAllImagesNotVisible(3); 
            drawMainMenu(); 
        }
    );
    
    jc("#"+graphics[j][1][1]+j).mouseover(
        function() {
            currentScreen = "pause bar";
            jc("#"+graphics[j][1][1]+j).visible(false);
            jc("#"+graphics[j][1][1]+"over"+j).visible(true);
            out("mouse over lol")
        }
    );
    
    jc("#"+graphics[j][1][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "pause bar" || currentScreen == "pause menu" || currentScreen == "help menu") {
                jc("#"+graphics[j][1][1]+"over"+j).visible(false);
                jc("#"+graphics[j][1][1]+j).visible(true);
                if (currentScreen == "pause bar") {
                    currentScreen = "game window"; 
                }
            }
        }
    );
}

function updateWind(){
    oldwind = wind
    wind = (Math.random()-0.5)*2;
    jc("#windarrow2").scale(wind/oldwind, 1, 500);
}

function randomPointsList(){
        points = new Array();
        points.push(new Array(0, Math.random() * 50 + 300));
        var i;
        for(i = 0; i < width; i++){
              
            speed += ((Math.random()- 0.5) /4 );
            if(speed > 1 ){
                speed = 1;
            }
        
            if(speed < -1 ){
                speed = -1;
            }
            if(points[i][1] < 250){
                speed += 0.05;
            }
            if(points[i][1] > 350){
                speed -= 0.05;
            }
            points.push(new Array(i+1, points[i][1] + speed));
        }
}

function drawTerrain(){
    
    terrain.push(jc.line(points));
    
    //r = parseInt(Math.random()*255)
    //g = parseInt(Math.random()*255)
    //b = parseInt(Math.random()*255)
    
    r = 0
    g = 100
    b = 255
    incr = (Math.random())
    incg = (Math.random()/10)
    incb = (Math.random())
    
    for (j = 0; j < points.length; j++){
        //r+=incr
        g+=incg
        b+=incb
        if ( r > 255) { r = 255; incr = -incr }
        if ( g > 255) { g = 255; incg = -incg }
        if ( b > 255) { b = 255; incb = -incb }
        if ( r < 0 ) { r = 0; incr = -incr }
        if ( g < 0 ) { g = 0; incg = -incg }
        if ( b < 0 ) { b = 0; incb = -incb }
        
        terrain.push(jc.line([points[j], [points[j][0], height]], "rgb("+parseInt(r)+","+parseInt(g)+","+parseInt(b)+")"))
    }
}

function downAll(list){
    for(i = 0; i < list.length; i++){
        list[i].down('bottom');
    }
}

function upAll(list){
    for(i = 0; i < list.length; i++){ 
        list[i].up('top');
    }
}

function delAll(list){
    for(i = list.length-1; i >= 0; i--){
        list[i].del();
        list.pop(list[i])
    }
}

function drawPauseMenu(){

    canv = document.getElementById("canvas");
    canv.style.cursor = "url(graphics/pawcursor.cur),crosshair"
    
    currentScreen = "pause menu"
    var j = 4 
    for (i = 0; i < graphics[j].length-3; i++) {
        jc("#"+graphics[j][i][1]+j).visible(true);
       // out(jc("#"+graphics[j][i][1]+j).level());
    }
    
    // go back to game if the Resume button is pressed
    jc("#"+graphics[j][1][1]+"over"+j).click(
        function() { 
            previousScreen = "pause menu"; 
            setAllImagesNotVisible(); 
            drawGameWindow(); 
        }
    );
    
    // glow effect for mouse over Resume Button
    jc("#"+graphics[j][1][1]+j).mouseover(
        function() {
            jc("#"+graphics[j][1][1]+j).visible(false);
            jc("#"+graphics[j][1][1]+"over"+j).visible(true);
        }
    );
    // no effect for mouse out Resume Button
    jc("#"+graphics[j][1][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "pause menu") {
                jc("#"+graphics[j][1][1]+"over"+j).visible(false);
                jc("#"+graphics[j][1][1]+j).visible(true);
            }
        }
    );
    
    
    // go to help menu if the Help button is pressed
    jc("#"+graphics[j][2][1]+"over"+j).click(
        function() {             
            previousScreen = "pause menu"; 
            setAllImagesNotVisible(4); 
            drawHelpMenu(); 
        }
    );
    
    // glow effect for mouse over Help Button
    jc("#"+graphics[j][2][1]+j).mouseover(
          function() {
            jc("#"+graphics[j][2][1]+j).visible(false);
              jc("#"+graphics[j][2][1]+"over"+j).visible(true);
              
          }
    );
    // no effect for mouse out Help Button
    jc("#"+graphics[j][2][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "pause menu") {
                jc("#"+graphics[j][2][1]+"over"+j).visible(false);
                jc("#"+graphics[j][2][1]+j).visible(true);
            }
        }
    );
    
    // go to Main menu if the Exit button is pressed
    jc("#"+graphics[j][3][1]+"over"+j).click(
        function() { 
            
            window.location.reload(true);
            
            deathFromTheSky()
            previousScreen = "pause menu"; 
            setAllImagesNotVisible(); 
            drawMainMenu(); 
        }
    );    
    
    // glow effect for mouse over Exit Button
    jc("#"+graphics[j][3][1]+j).mouseover(
        function() {
            jc("#"+graphics[j][3][1]+j).visible(false);
            jc("#"+graphics[j][3][1]+"over"+j).visible(true);
        }
    );
    // no effect for mouse out Exit Button
    jc("#"+graphics[j][3][1]+"over"+j).mouseout(
        function() {
            if (currentScreen == "pause menu") {
                jc("#"+graphics[j][3][1]+"over"+j).visible(false);
                jc("#"+graphics[j][3][1]+j).visible(true);
            }
        }
    );
}

function drawEpicWinMenu(){
    out("Good job, you won!")
    deathFromTheSky()
    currentScreen = "epicwin menu";
    
    var j = 9 
    for (i=0; i < graphics[j].length; i++){
       jc("#"+graphics[j][i][1]+j).visible(true)    
    } 
    
    
    currentScreen = "main menu";
    location.reload();
    drawMainMenu()
}

function drawGameOverMenu(){
    //alert("Aw, you lose! Q_Q GAME OVER.")
    
    currentScreen = "gameover menu"
    
    var j = 10
	
    for (i = 0; i < graphics[j].length; i++){
        jc("#"+graphics[j][i][1]+j).visible(true);
    }
    
    deathFromTheSky()
    location.reload();
    drawMainMenu()
}




function Penguin(x, y){
    this.x = parseInt(x);
    this.y = parseInt(y);
    if (x == null || y == null) { out ('i hate you'); }
    this.id = '#penguin'+penguins.length
    this.hp = 100;
    
    this.type = null;
    
    this.image = jc.image(graphics[5][0][0], this.x-25, this.y-45).id('penguin'+penguins.length);
    jc(this.id).scale(0.5);
    
    this.text = jc.text(this.hp, this.x-17, this.y-54, 'rgb(50, 205, 50)', true).id("penguintext"+penguins.length);
   
    jc("#penguintext"+penguins.length).font(font);
    
    this.rect = jc.rect(x-19, y-70, 39, 18, 'rgb(50, 205, 50)');    
    
    penguins.push(this);
    
    
    this.shoot = function (x2, y2) {
        if (!isShooting) {
            bullet = new Bullet(x+15, y-50, x2, y2);
        }
    }
    
    this.del = function () {
        this.image.del();
        this.text.del();
        this.rect.del();
    }
    
    this.pwn = function () {
        this.image.del();
        this.text.del();
        this.rect.del();
        new Tombstone(x, y+15, 'penguin');
    }
    
}



function Panda(x, y){
    this.x = parseInt(x);
    this.y = parseInt(y);
    if (x == null || y == null) {
        out ('i hate you');
    }
    this.id = '#panda'+enemies.length
    this.hp = 100;
    
    this.type = null;
    this.image = jc.image(graphics[6][0][0], this.x-25, this.y-45).id('panda'+enemies.length);
    jc(this.id).scale(0.5);
    //jc("#panda").rotate(130, this.x, this.y)
    
    this.text = jc.text(this.hp, this.x, this.y-60, 'rgb(50,205,50)', true).id("pandatext"+enemies.length);
    jc("#pandatext"+enemies.length).font(font);
    
    this.rect = jc.rect(x-2, y-76, 39, 18, 'rgb(50, 205, 50)');
    
    fancystuff.push(this.text)
    fancystuff.push(this.rect)
    
    enemies.push(this)
    
    this.shoot = function (x2, y2) {
        if (!isShooting) {
            bullet = new Bullet(x+5, y-60, x2, y2);
        }
    }
    
    this.del = function () {
        this.image.del();
        this.text.del();
        this.rect.del();
    }
    
    this.pwn = function () {
        //enemies.pop(this);
        this.image.del();
        this.text.del();
        this.rect.del();
        new Tombstone(x, y, 'panda');
    }
}

function Bullet(x, y, x2, y2){
    this.x = x;
    this.y = y;
    this.width = graphics[7][0][0].width;
    this.height = graphics[7][0][0].height;
    vx = this.vx = (x2 - x)/25 + wind;
    vy = this.vy = (y2 - y)/25;
    var id = this.id = '#bullet'+bullets.length;
    
    
    
    this.type = null;
    
    this.image = jc.image(graphics[7][0][0], parseInt(x-width/2), parseInt(y-height/2)).id('bullet'+bullets.length);
    jc(this.id).scale(0.5);
    jc(this.id).visible(true);
    
    bullets.push(this);
    fancystuff.push(this.image);
    
    isShooting = true;
    
    //out('created object '+this.id+' at ('+this.x+', '+this.y+')');
    var loop = setInterval(function() {
    
        if (currentScreen == "game window" || currentScreen == "pause bar") {
        
            if (parseInt(x+15) > 640) {x -= 640}
            if (parseInt(x+15) < 0) {x += 640}
            
            if (y + 25 > points[parseInt(x+15)][1] || y + 25 > 480) {
                boom = jc.image(graphics[7][1][0], parseInt(x), parseInt(y)).id("boom");
                fancystuff.push(boom);
                jc("#boom").scale(0.5);
                jc("#boom").animate(
                    {height:150, width:150, x:parseInt(x)-35, y:parseInt(y)-36}, 
                    500, 
                    function(){
                        fancystuff.pop(boom);
                        jc("#boom").del(); 
                        isShooting = false;
                        updateWind();
                        
                        // === fa un massacro ===
                        
                        for (i = 0; i < penguins.length; i++) {
                            distance = Math.abs(x - penguins[i].x)
                            if (distance < 50) {
                                penguins[i].hp -= parseInt(50 - distance);
                                out("Updating penguin #"+i+" hp to: "+penguins[i].hp);
                                if(penguins[i].hp < 100){
                                    penguins[i].text.del()
                                    penguins[i].rect.del()
                                    if(penguins[i].hp < 10){
                                        penguins[i].text = jc.text(penguins[i].hp, penguins[i].x-6, penguins[i].y-54, 'rgb(255, 0, 0)', true).id("penguintext"+i);
                                        penguins[i].text.font(font)
                                        penguins[i].rect = jc.rect(penguins[i].x-19, penguins[i].y-70, 39, 18, 'rgb(255,0,0)');
 
                                    }
                                    else{
                                      if(penguins[i].hp  >= 70){
                                         penguins[i].text = jc.text(penguins[i].hp, penguins[i].x-10, penguins[i].y-54, 'rgb(50,205,50)', true).id("penguintext"+i);
                                         penguins[i].text.font(font)
                                         penguins[i].rect = jc.rect(penguins[i].x-19, penguins[i].y-70, 39, 18, 'rgb(50,205,50)');


                                      }  
                                      if(penguins[i].hp < 70 && penguins[i] && penguins[i].hp > 30){
                                         penguins[i].text = jc.text(penguins[i].hp, penguins[i].x-10, penguins[i].y-54, 'rgb(255, 140, 0)', true).id("penguintext"+i);
                                         penguins[i].text.font(font)
                                         penguins[i].rect = jc.rect(penguins[i].x-19, penguins[i].y-70, 39, 18, 'rgb(255,140,0)');

                                      }    
                                      if(penguins[i].hp < 30){
                                         penguins[i].text = jc.text(penguins[i].hp, penguins[i].x-10, penguins[i].y-54, 'rgb(255, 0, 0)', true).id("penguintext"+i);
                                         penguins[i].text.font(font)
                                         penguins[i].rect = jc.rect(penguins[i].x-19, penguins[i].y-70, 39, 18, 'rgb(255,0,0)');
                                      }
                                       
                                    }
                                    
                                } 

                                if (penguins[i].hp <= 0) {
                                    penguins[i].hp = 0;
                                    jc("#penguintext"+i).string(penguins[i].hp)
                                    penguins[i].pwn();
                                    
                                } else {
                                    jc("#penguintext"+i).string(penguins[i].hp)
                                }
                            }
                        }
                        
                        
                        for ( i = 0; i < enemies.length; i++){
                            distance = Math.abs(x - enemies[i].x);
                            if( distance < 50 ){
                                enemies[i].hp -= parseInt(50 - distance);
                                out("Updating enemy #"+i+" hp to: "+enemies[i].hp);
                                if(enemies[i].hp < 100){
                                    enemies[i].text.del();
                                    enemies[i].rect.del();
                                    if(enemies[i].hp < 10){
                                        enemies[i].text = jc.text(enemies[i].hp, enemies[i].x+12, enemies[i].y-60, 'rgb(255, 0, 0)', true).id("penguintext"+i);
                                        enemies[i].text.font(font) 
                                        enemies[i].rect = jc.rect(enemies[i].x-2, enemies[i].y-76, 39, 18, 'rgb(255,0,0)');


                                    }
                                    else{
                                        if(enemies[i].hp  >= 70){
                                        enemies[i].text = jc.text(enemies[i].hp, enemies[i].x+6, enemies[i].y-60, 'rgb(50,205,50)', true).id("penguintext"+i);
                                        enemies[i].text.font(font)
                                        enemies[i].rect = jc.rect(enemies[i].x-2, enemies[i].y-76, 39, 18, 'rgb(50,205,50)');


                                        }  
                                        if(enemies[i].hp < 70 && enemies[i] && enemies[i].hp > 30){
                                            enemies[i].text = jc.text(enemies[i].hp, enemies[i].x+6, enemies[i].y-60, 'rgb(255, 140, 0)', true).id("penguintext"+i);
                                            enemies[i].text.font(font)
                                            enemies[i].rect = jc.rect(enemies[i].x-2, enemies[i].y-76, 39, 18, 'rgb(255,140,0)');
                                        }    
                                        if(enemies[i].hp < 30){
                                            enemies[i].text = jc.text(enemies[i].hp, enemies[i].x+6, enemies[i].y-60, 'rgb(255, 0, 0)', true).id("penguintext"+i);
                                            enemies[i].text.font(font)
                                            enemies[i].rect = jc.rect(enemies[i].x-2, enemies[i].y-76, 39, 18, 'rgb(255,0,0)');     
                                        }
                                    }
                                } 
                                if (enemies[i].hp <= 0) {
                                    enemies[i].hp = 0
                                    jc("#pandatext"+i).string(enemies[i].hp);
                                    enemies[i].pwn();
                                }
                                else{
                                   jc("#pandatext"+i).string(enemies[i].hp);
                                }
                                
                            }
                        }
                        
                        
                        if (winCheck()) {
                            // out('winscreen');
                            setAllImagesNotVisible(); 
                            drawEpicWinMenu();
                        }
                
                        else if (loseCheck()) {
                            // out('losescreen');
                            setAllImagesNotVisible();
                            drawGameOverMenu();
                        }      
						
						else if (myTurn) {
                            if (penguinsTurnCounter >= penguins.length) {penguinsTurnCounter = 0;}
							while (penguins[penguinsTurnCounter].hp == 0) {
                                penguinsTurnCounter++;
                                if (penguinsTurnCounter >= penguins.length) {penguinsTurnCounter = 0;}
                            }
							pointer = new Pointer(penguins[penguinsTurnCounter].x, penguins[penguinsTurnCounter].y)
						}
						else {
                            if (enemiesTurnCounter >= enemies.length) {enemiesTurnCounter = 0;}
							while (enemies[enemiesTurnCounter].hp == 0) {
                                enemiesTurnCounter++;
                                if (enemiesTurnCounter >= enemies.length) {enemiesTurnCounter = 0;}
                            }
							pointer = new Pointer(enemies[enemiesTurnCounter].x+17, enemies[enemiesTurnCounter].y)
						}
						
                        // ======================
                    }
                )
                clearInterval(loop);
                fancystuff.pop(this)
                jc(id).del();
                
                
            }
            else {
                x += vx;
                y += vy;
                vy += gravity;
                //jc(id).rotate(15, parseInt(x), parseInt(y)) 
                jc(id).translateTo(parseInt(x), parseInt(y));
                
            }
        }
	}, 10); //10 msec
}


function winCheck() {
    for (i=0; i<enemies.length; i++) {
        if (enemies[i].hp > 0) {
           // out('checking win')
            return false
        }
    }
    return true
}

function loseCheck() {
    for (i=0; i<penguins.length; i++) {
        if (penguins[i].hp > 0) {
          //  out('checking lose')
            return false
        }
    }
    return true
}

function Tombstone(x, y, type) {
    this.x = x;
    this.y = y;
    
    this.type = type;
    
    if (this.type == 'penguin') {
        
        this.width = graphics[8][0][0].width;
        this.height = graphics[8][0][0].height;
        var id = this.id = '#tombstone_penguin'+tombstones.length;
        this.image = jc.image(graphics[8][0][0], parseInt(x-this.width/2), parseInt(y-this.height/2)).id('tombstone_penguin'+tombstones.length);
    }
    if (this.type == 'panda') {
        this.width = graphics[8][1][0].width;
        this.height = graphics[8][1][0].height;
        var id = this.id = '#tombstone_panda'+tombstones.length;
        this.image = jc.image(graphics[8][1][0], parseInt(x-this.width/2), parseInt(y-this.height/2)).id('tombstone_panda'+tombstones.length);
    }
    
    jc(this.id).scale(0.5);
    jc(this.id).visible(true);
    
    tombstones.push(this);
    fancystuff.push(this.image);
    
    this.del = function () {
        this.image.del();
    }
    
}

function Pointer(x, y) {
	this.x = x;
	this.y = y;
	
	this.width = graphics[8][2][0].width;
	this.height = graphics[8][2][0].height;
	var id = this.id = "#pointer";
	this.image = jc.image(graphics[8][2][0], parseInt(x-this.width/2), parseInt(y-120)).id("pointer");
	
	jc(this.id).visible(true);
	
	fancystuff.push(this.image);
	
	this.del = function () {
		fancystuff.pop(this.image)
		this.image.del();
	}
}


function ImageLoader() {   
    
    for ( j=0; j<graphics.length; j++ ) {
        for (i=0; i<graphics[j].length; i++) { // loop for the initialization/creation of the images
            graphics[j][i][0] = new Image();
            graphics[j][i][0].src = graphicsPath+graphics[j][i][1]+".png";
            
            imageLoadTotal++;
           // out(graphicsPath+graphics[j][i][1]+".png")
            
            graphics[j][i][0].onload = function () { 
               // out("loaded "+imageLoadCounter+" of "+imageLoadTotal);
                imageLoadCounter++; 
            }
            
        }
    }
}
    
function waitForImageLoad() {
	if (imageLoadCounter >= imageLoadTotal) {
        //out("loaded "+imageLoadCounter+" of "+imageLoadTotal+", finished loading")
		main();
	} else {
		setTimeout("waitForImageLoad()", 20);
	}
}

function eventMouseClick(e) {
    var x = e.offsetX;
    var y = e.offsetY;
    
    // Mouse button events, 0 = left click; 1 = middle click; 2 = right click.
    if (e.button == 0 || e.button == 1 || e.button == 2) {
        // left button clicked
        if (currentScreen == "game window") {
			pointer.del();
            if (myTurn) {
                if (penguinsTurnCounter >= penguins.length) {penguinsTurnCounter = 0;}
                while (penguins[penguinsTurnCounter].hp == 0) {
                    penguinsTurnCounter++;
                    if (penguinsTurnCounter >= penguins.length) {penguinsTurnCounter = 0;}
                }
                penguins[penguinsTurnCounter].shoot(x, y);
                penguinsTurnCounter += 1;
            }
            else {
                if (enemiesTurnCounter >= enemies.length) {enemiesTurnCounter = 0;}
                while (enemies[enemiesTurnCounter].hp == 0) {
                    enemiesTurnCounter++;
                    if (enemiesTurnCounter >= enemies.length) {enemiesTurnCounter = 0;}
                }
                enemies[enemiesTurnCounter].shoot(x, y);
                enemiesTurnCounter += 1;
            }
            myTurn = !myTurn
        }
        
    }

}

function eventMouseMove(e) {
    if (currentScreen != "game window") {
        return;
    }
    
    mouseX = e.offsetX;
    mouseY = e.offsetY;
    
    if (myTurn) {
        
        targetX = penguins[penguinsTurnCounter].x
        targetY = penguins[penguinsTurnCounter].y
        
    }
    else {
    
        targetX = enemies[enemiesTurnCounter].x
        targetY = enemies[enemiesTurnCounter].y
        
    }
    
    
    // POWER BAR
    distance = Math.sqrt( Math.pow( mouseX-targetX, 2 ) + Math.pow( mouseY-targetY, 2) );  
    reduction = distance/3
    clip = jc.rect(30, 440, reduction, 15);
    jc("#powerBar").clip(clip);
    
    // ANGLE
    angle = -(Math.atan2((mouseY-targetY),(mouseX-targetX)))*(180/Math.PI)
    
    jc("#angle").rotate(directionAngle-angle, directionX, directionY)
    
    directionAngle = angle
    
    
}

function restorePaw(){
    canv = document.getElementById("canvas");
    canv.style.cursor = "url(graphics/pawcursor.cur),crosshair";
}

function deathFromTheSky(){
    delAll(terrain);
    delAll(penguins);
    delAll(enemies);
    delAll(fancystuff);

    myTurn = true;
    penguinsTurnCounter = 0;
    enemiesTurnCounter = 0;

    points = new Array();
    terrain = new Array();
    fancystuff = new Array();
    penguins = new Array();
    enemies = new Array();
    bullets = new Array();
    tombstones = new Array();

    pointer = null;

    isShooting = false;
}

window.addEventListener("load", init, false);



// Debugging function. Use it to print on the terminal
function out(message) {
	try {
        console.log(message);
    }
    catch (exception) {
        return "LOL ERRORZ";
    }
}
